package com.sync.syncmasterdata.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * bip 数据源链接
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySeven",
        transactionManagerRef="transactionManagerSeven",
        basePackages= {"com.sync.syncmasterdata.customer.repository.biprep","com.sync.syncmasterdata.vendor.repository.biprep","com.sync.syncmasterdata.product.repository.bip"})//设置dao（repo）所在位置
public class SevenConfig {
    @Autowired
    @Qualifier("dataSourceSeven")
    private DataSource sevenDataSource;

    @Autowired
    @Qualifier("vendorProperties")
    private Map<String, Object> vendorProperties;


    @Bean(name = "entityManagerFactorySeven")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySeven(EntityManagerFactoryBuilder builder) {
        // 显式设置 Hibernate 属性
        Map<String, Object> jpaProperties = new HashMap<>();
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle12cDialect");
        jpaProperties.put("hibernate.hbm2ddl.auto", "validate");

        LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
                .dataSource(sevenDataSource)
                .properties(jpaProperties)
                .packages("com.sync.syncmasterdata.customer.entity.bip","com.sync.syncmasterdata.vendor.entity.bip","com.sync.syncmasterdata.product.entity.bip")
                .persistenceUnit("sevenPersistenceUnit")
                .build();
        return entityManagerFactory;
    }

    @Bean(name = "entityManagerSeven")
    public EntityManager entityManagerSeven(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySeven(builder).getObject().createEntityManager();
    }


    @Bean(name = "transactionManagerSeven")
    PlatformTransactionManager transactionManagerSeven(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySeven(builder).getObject());
    }

}
